// 向Url添加参数

/**
 * 向 url 添加 query 参数
 *
 * @param {string} targetUrl
 * @param {object} params
 */

function addQueryParam(targetUrl, params) {
    let newRrl = ""
    // 处理targetUrl
    let domain = "",
        search = "",
        hash = "";
    let searchIndex = targetUrl.indexOf("?") > 0 ? targetUrl.indexOf("?") : 0;
    let hashIndex = targetUrl.indexOf("#") > 0 ? targetUrl.indexOf("#") : 0;

    if (targetUrl.length) {
        if (searchIndex && hashIndex) {
            domain = targetUrl.substring(0, searchIndex)
            search = targetUrl.substring(searchIndex + 1, hashIndex)
            hash = targetUrl.substring(hashIndex)
        }
        if (!searchIndex && !hashIndex) {
            domain = targetUrl.substring(0);
        }
        if (searchIndex && !hashIndex) {
            domain = targetUrl.substring(0, searchIndex);
            search = targetUrl.substring(searchIndex + 1)
        }
        if (!searchIndex && hashIndex) {
            domain = targetUrl.substring(0, hashIndex);
            hash = targetUrl.substring(hashIndex)
        }
    }

    // 处理参数，及去重，生成新对象
    let searchObj = {};
    let name = null,
        value = null;
    const searchArr = search.length ? search.split('&') : []
    const len = searchArr.length;
    for (let i = 0; i < len; i++) {
        item = searchArr[i].split("=");
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        if (name.length) {
            searchObj[name] = value
        }
    }
    const obj = {
        ...searchObj,
        ...params
    }

    // 将对象生成参数
    const paramsArr = []
    for ([key, value] of Object.entries(obj)) {
        paramsArr.push(`${key}=${value}`)
    }
    const searchStr = paramsArr.length ? paramsArr.join("&") : "";


    // 组合参数
    newRrl = `${domain}?${searchStr}${hash}`

    return newRrl || targetUrl

}

const cc = addQueryParam("http://taobao.com", {
    b: 5,
    a: '6'
})

console.log(cc)